import os.path

from tools.file_manager import gen_data_name
import pandas as pd

from tools.framework import get_ui_value
from core.constant import *
from module.static_module.parent.model import AdditionModule


class OrderIntegrationModel(AdditionModule):
    def __init__(self, master):
        super().__init__(master, Module.OrderIntegration)
        # 实体类映射视图类变量数据
        self.order_file_ls = []  # 订单文件
        self.mk_data_file_ls = []  # 行情文件

        # 映射视图类变量数据默认值
        self.order_file = None  # 订单文件
        self.mk_data_file = None  # 行情文件
        # 实体类结构变量
        self.sub_view = None

    def sec_init(self):
        # 实体类映射视图类变量数据
        self.order_file_ls = []  # 订单文件
        self.mk_data_file_ls = []  # 行情文件
        from module.addition_module.order_integration.view import OrderIntegrationView
        self.sub_view = OrderIntegrationView(self)

    def get_ui_params(self):
        # 获取ui界面的相关参数
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.OrderFile)
        self.order_file = get_ui_value(values, indices, WidgetCategory.Entry)
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.MkDataFile)
        self.mk_data_file = get_ui_value(values, indices, WidgetCategory.Entry)

    def on_ok(self):
        self.get_ui_params()
        # 获取基本信息
        order_file_path = self.order_file  # 订单文件路径
        mk_data_file_path = self.mk_data_file  # 行情文件路径
        # 读取行情和订单文件
        order_data: pd.DataFrame = self.master.file_manager.read_csv(order_file_path)
        mk_data_dc = self.master.file_manager.read_dc_csv(mk_data_file_path)
        # 将订单信息加入mk_data
        for index_o, row in order_data.iterrows():
            symbol = row["symbol"]
            mk_data = mk_data_dc[symbol]

            # 找到距order最近的后一个时间，找不到pass
            filtered_equity = mk_data[mk_data.index >= index_o]
            if filtered_equity.empty:
                pass
            else:
                index_equity = filtered_equity.index[0]
                direction = "buy" if row["direction"] == "Direction.LONG" else "sell"
                price = row["price"]
                # 加入
                mk_data.loc[index_equity, direction] = price

        # 整合新路径
        mkftsg_path = self.master.file_manager.market_factor_signal_data_path
        base_name = gen_data_name(DataCategory.MkFtSg) + ".csv"
        mkftsg_file_path = os.path.join(mkftsg_path, base_name)
        self.master.file_manager.save_dc_csv(mk_data_dc, mkftsg_file_path)

        pass
